<template>
    <page-box>
        <template v-slot:header>
            <ask-breadcrumb>
                <template v-for="(item, index) in $getBreadCrumbsName($route.path)">
                    <ask-breadcrumb-item :key="index" v-if="item.path" :to="'/' + item.path">{{ item.meta.title }}</ask-breadcrumb-item>
                    <ask-breadcrumb-item :key="index" v-else>{{ item.meta.title }}</ask-breadcrumb-item>
                </template>
                <ask-breadcrumb-item to="/module-manage/village-collection-task" v-if="$route.query.taskType">{{ $route.query.taskType === "collect" ? "待填报的任务" : '抄送我的任务' }}</ask-breadcrumb-item>
                <ask-breadcrumb-item name="VillageDeclareDetail"></ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <div class="task-detail-header">
            <div class="title">
                <p class="name">
                    {{ tableName }}
                    <span :class="{ finish: _isFinish }">
                        {{ $route.query.taskId ? _isFinish ? "已审批" : "待审批" : _isFinish ? "已完成" : "进行中" }}
                    </span>
                </p>
                <el-tooltip
                    v-if="Number($route.query.descriptionType) === 1"
                    effect="dark"
                    :content="$route.query.description"
                    :disabled="!$route.query.description"
                    placement="top">
                    <p class="description">{{ $route.query.description || "暂无描述" }}</p>
                </el-tooltip>
                <p class="btn" v-if="Number($route.query.descriptionType) === 2" @click="showRichText">查看表单介绍</p>
            </div>
            <div>
                <el-button @click="goBack">返回</el-button>
                <template v-if="!_isFinish && $route.query.taskType === 'collect'">
                    <el-button type="primary" @click="assignRow">指派</el-button>
                    <el-button type="primary" @click="fillInRow">填报</el-button>
                    <el-popover placement="bottom" width="260" trigger="click">
                        <div class="step-import">
                            <div class="step1">
                                <el-link type="primary" @click="downTemplate({formName: $route.query.name, formId: currentForm.formId})">下载模板</el-link>
                                <div>请先下载模板，根据模板填写后导入。<br />部分复杂表格格式暂不支持导入，请完成导入后进入详情页面手动添加。</div>
                            </div>
                            <upLoad-normal
                                :accept="'.xlsx'"
                                :isSingle="true"
                                @httpRequest="httpRequest">
                                <el-link type="primary">导入excel</el-link>
                            </upLoad-normal>
                        </div>
                        <el-button slot="reference" type="primary" class="import-btn">导入</el-button>
                    </el-popover>
                    <el-button type="primary" @click="completeTask">提交</el-button>
                </template>
            </div>
        </div>
        <div class="task-detail-container">
            <div class="left">
                <el-table
                    v-show="tableData.length"
                    ref="multipleTable"
                    :data="tableData"
                    class="pbb__table isSingle"
                    header-cell-class-name="pbb__table-thead"
                    cell-class-name="pbb__table-thead-cell"
                    row-class-name="pbb__table-thead-row"
                    row-key="id"
                    style="width: 100%;height: 100%;"
                    @select="changeSelectRow">
                    <el-table-column
                        v-if="$route.query.taskType === 'collect'"
                        :label="$route.query.status.toString() === '1' ? '数据状态' : '审核状态'"
                        align="center"
                        type="index"
                        width="100">
                        <template slot-scope="scope">
                            <span style="color: #00b160" v-if="scope.row.verify === 3">已确认</span>
                            <span style="color: #067bff" v-if="scope.row.verify === 1">待确认</span>
                            <el-tooltip
                                class="item"
                                effect="dark"
                                :disabled="!scope.row.verifyCause"
                                :content="scope.row.verifyCause"
                                placement="top">
                                <span style="color:#de2728" v-if="scope.row.verify === 0">有误<i class="el-icon-warning"></i></span>
                            </el-tooltip>
                            <span v-if="scope.row.verify === 2">草稿</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="序号"
                        align="center"
                        type="index"
                        width="60">
                    </el-table-column>
                    <el-table-column
                        v-for="(item, index) in tableColumn"
                        :key="index"
                        :prop="item.prop"
                        :label="item.name"
                        :show-overflow-tooltip="[3, 4, 6, 7, 12].includes(item.valueKindId)"
                        :min-width="[3, 11].includes(item.valueKindId) ? '200px' : [5, 8].includes(item.valueKindId) ? '140px' : (item.name.length * 16 + 20) > 140 ? (item.name.length * 16 + 20 + 'px') : '140px'">
                        <template slot-scope="scope">
                            <div v-if="item.itemType === 1">
                                <el-link type="primary" @click="showChildTable(item, scope.$index)">查看详细</el-link>
                            </div>
                            <template v-else-if="item.valueKindId === 4" class="address-text">
                                {{ scope.row[item.prop] ? scope.row[item.prop].cityName : "" }}
                                {{ scope.row[item.prop] && scope.row[item.prop].cityAddress ? scope.row[item.prop].cityAddress : "" }}
                            </template>
                            <div v-else-if="item.valueKindId === 5">
                                <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
                                    <img class="table-img" :src="$staticUrl + '/' + scope.row[item.prop][0]" alt="" @click="previewImg(scope.row[item.prop])"/>
                                </div>
                            </div>
                            <div v-else-if="item.valueKindId === 8">
                                <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
<!--                                    <video class="table-img" :src="$staticUrl + '/' + scope.row[item.prop][0]" alt="" @click="previewVideo(scope.row[item.prop])"></video>-->
                                    <el-buttom @click="previewVideo(scope.row[item.prop])">点击播放</el-buttom>
                                </div>
                            </div>
                            <div v-else-if="item.valueKindId === 9">
                                <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
                                    <el-button type="text" @click="previewVideo(scope.row[item.prop])">播放</el-button>
                                </div>
                            </div>
                            <div v-else-if="item.valueKindId === 10">
                                <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
                                    <el-link
                                        class="table-file"
                                        v-for="(it, idx) in scope.row[item.prop]"
                                        :key="idx"
                                        type="primary"
                                        :href="$staticUrl + '/' + it"
                                        target="_blank">
                                        文件{{ idx + 1 }}
                                    </el-link>
                                </div>
                            </div>
                            <span v-else class="other-span" :title="scope.row[item.prop]">{{ scope.row[item.prop] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="!_isFinish && $route.query.taskType === 'collect'"
                        label="操作"
                        width="100">
                        <template slot-scope="scope">
                            <template v-if="scope.row.verify !== 3">
                                <el-button @click="editRow(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="deleteRow(scope.row)" type="text" size="small">删除</el-button>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
                <ask-empty-text style="min-height: 400px;" v-if="tableData.length === 0"></ask-empty-text>
            </div>
        </div>
        <el-dialog
            :title="ChildTableTitle"
            :visible.sync="showChild"
            :close-on-click-modal="false">
            <el-table :data="ChildTableData">
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                    width="60">
                </el-table-column>
                <el-table-column
                    v-for="(item, index) in ChildTableColumn"
                    :key="index"
                    :prop="item.prop"
                    :label="item.name"
                    :show-overflow-tooltip="[3, 4, 6, 7, 12].includes(item.valueKindId)"
                    :min-width="[3, 11].includes(item.valueKindId) ? '200px' : [5, 8].includes(item.valueKindId) ? '140px' : (item.name.length * 16 + 20) > 140 ? (item.name.length * 16 + 20 + 'px') : '140px'">
                    <template slot-scope="scope">
                        <template v-if="item.valueKindId === 4" class="address-text">
                            {{ scope.row[item.prop] ? scope.row[item.prop].cityName : "" }}
                            {{ scope.row[item.prop] && scope.row[item.prop].cityAddress ? scope.row[item.prop].cityAddress : "" }}
                        </template>
                        <div v-else-if="item.valueKindId === 5">
                            <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
                                <img class="table-img" :src="$staticUrl + '/' + scope.row[item.prop][0]" alt="" @click="previewImg(scope.row[item.prop])"/>
                            </div>
                        </div>
                        <div v-else-if="item.valueKindId === 8">
                            <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
<!--                                <video class="table-img" :src="$staticUrl + '/' + scope.row[item.prop][0]" alt="" @click="previewVideo(scope.row[item.prop])"></video>-->
                                <el-buttom @click="previewVideo(scope.row[item.prop])">点击播放</el-buttom>
                            </div>
                        </div>
                        <div v-else-if="item.valueKindId === 9">
                            <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
                                <el-button type="text" @click="previewVideo(scope.row[item.prop])">播放</el-button>
                            </div>
                        </div>
                        <div v-else-if="item.valueKindId === 10">
                            <div v-if="scope.row[item.prop] && scope.row[item.prop].length">
                                <el-link
                                    class="table-file"
                                    v-for="(it, idx) in scope.row[item.prop]"
                                    :key="idx"
                                    type="primary"
                                    :href="$staticUrl + '/' + it"
                                    target="_blank">
                                    文件{{ idx + 1 }}
                                </el-link>
                            </div>
                        </div>
                        <span v-else class="other-span" :title="scope.row[item.prop]">{{ scope.row[item.prop] }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <template v-slot:footer v-if="total > 0">
            <pagination :total="total" :page.sync="pageIndex" :limit.sync="pageSize" @pagination="getTable"/>
        </template>
        <el-dialog
            title="表单介绍详情"
            :visible.sync="dialogVisible"
            width="30%"
            class="rich-dialog">
            <div>
                <p class="titleName"><span>标题:</span>{{ tableName }}</p>
                <div v-html="$route.query.description" class="centent"></div>
            </div>
        </el-dialog>
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import DownLoadTemplateUpLoadMixins from "./mixins";
import UpLoadNormal from "@/components/upload-normal/index.vue";
import { dialogPreviewImg } from "@/components/public/preview-img/index";
import { dialogPreviewVideoAudio } from "@/components/public/preview-video-audio/index";
import { dialogSelect } from "@/views/process-manage/src/components/person-selection/index";
import { State } from "vuex-class";
import { localStorage } from "@/utils";

@Component({
    name: "DeclareDetailNotAlive",
    components: {
        UpLoadNormal
    }
})
export default class DeclareDetail extends Mixins(DownLoadTemplateUpLoadMixins) {
    @State(state => state.authArea) authArea: any;
    @State(state => state.user.userInfo) user: any;
    // 表格名称
    tableName: any = "";
    // 数据总数
    total = 0;
    // 每页数量
    pageSize = 10;
    // 当前页码
    pageIndex = 1;
    // 表格数据
    tableData: any[] = [];
    // 动态表头
    tableColumn: any = [];
    // 所有数据
    allData: any = [];
    // 选中内容
    selectedList: any = [];
    // 显示导出选项
    previewVideoItem: any = {
        url: "",
        type: ""
    };

    select: any = [];

    ChildTableData: any[] = [];
    ChildTableColumn: any[] = [];
    ChildTableTitle = "";
    showChild = false;
    dialogVisible = false;

    get _isFinish() {
        return this.$route.query.status ? this.$route.query.status.toString() === "2" : false;
    }

    created() {
        this.currentForm.formId = this.$route.query.formId || "";
        this.currentForm.processInstanceId =
            this.$route.query.processInstanceId || "";
        this.initPage();
    }

    initPage() {
        this.getTableTitle();
        this.getTable();
        this.tableName = this.$route.query.name;
    }

    // 展示富文本
    showRichText() {
        this.dialogVisible = true;
    }

    async getTableTitle() {
        const res = await this.$server["moduleManage/collection/title"]({
            data: {
                formId: this.$route.query.formId
            }
        });
        if (res.data.code === 200) {
            const column: any[] = [];
            this.tableColumn = [];
            this.tableColumn.push(...this.buildData(res.data.data));
            this.tableColumn = this.tableColumn.map((item: any) => {
                return {
                    ...item,
                    name: item.unitKindName ? item.name + "(" + item.unitKindName + ")" : item.name,
                    prop: item.itemType === 1 ? item.childrenFormId : item.id
                };
            });
            this.tableColumn = column.concat([], this.tableColumn);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    buildData(list: any) {
        const tableColumn: any[] = [];
        list.forEach((item: any) => {
            if (item.itemType === 0) {
                tableColumn.push(...this.buildData(item.items));
            } else {
                tableColumn.push(item);
            }
        });
        return tableColumn;
    }

    async getTable() {
        const url = this.$route.query.taskType === "collect" ? "moduleManage/collection/data" : "moduleManage/collection/all/flowData";
        const data = this.$route.query.taskType === "collect" ? {
            formId: this.$route.query.formId,
            currentPage: this.pageIndex,
            pageSize: this.pageSize,
            collectorId: this.$route.query.assigneeId,
            processInstId: this.$route.query.processInstanceId
        } : {
            formId: this.$route.query.formId,
            currentPage: this.pageIndex,
            pageSize: this.pageSize,
            processInstIds: localStorage.getItem("childTask").split(",")
        };
        const res = await this.$server[url]({
            data
        });
        if (res.data.code === 200) {
            this.tableData = [];
            this.allData = res.data.data.records;
            res.data.data.records.forEach((item: any) => {
                const row = {
                    ...item
                };
                item.itemDataList.forEach((it: any) => {
                    if (["4", "5", "8", "9", "10"].includes(it.valueKindId.toString())) {
                        row[it.itemId] = it.extData || [];
                    } else {
                        row[it.itemId] = it.itemValue || "";
                    }
                });
                this.tableData.push(row);
            });
            this.total = res.data.data.total;
            setTimeout(() => {
                this.$nextTick(() => {
                    if (this.$refs.multipleTable) {
                        (this.$refs.multipleTable as any).doLayout();
                    }
                });
            }, 300);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 查看子表数据
    showChildTable(column: any, lineNum: any) {
        this.ChildTableColumn = column.items.map((item: any) => {
            return {
                ...item,
                name: item.unitKindName ? item.name + "(" + item.unitKindName + ")" : item.name,
                prop: item.id
            };
        });
        // 子表表头id
        const columnId = column.items.map((item: any) => item.id);
        this.ChildTableData = [];
        this.ChildTableTitle = column.name;
        // 这行这个单元格子表的所有数据
        const rowColumnData: any = [];
        this.allData[lineNum].dataList.forEach((item: any) => {
            if (columnId.includes(item.itemId)) {
                rowColumnData.push(item);
            }
        });
        const data: any[] = [];
        let n = 1;
        const getRow = (n: any) => {
            return rowColumnData.filter((item: any) => item.lineNum === n);
        };
        rowColumnData.forEach(() => {
            if (getRow(n).length) {
                data.push(getRow(n));
                n++;
            }
        });
        data.forEach((item: any) => {
            const row = {};
            item.forEach((it: any) => {
                if ([4, 5, 8, 9, 10].includes(it.valueKindId)) {
                    row[it.itemId] = it.extData || [];
                } else {
                    row[it.itemId] = it.itemValue || "";
                }
            });
            this.ChildTableData.push(row);
        });
        this.showChild = true;
    }

    // 选中变化(单选的)
    changeSelectRow(val: any, row: any) {
        if (val.length === 1 || val.length === 0) {
            this.selectedList = val;
        } else if (val.includes(row)) {
            this.selectedList = [row];
            (this.$refs.multipleTable as any).clearSelection();
            (this.$refs.multipleTable as any).toggleRowSelection(row);
        }
    }

    // 图片预览
    previewImg(urls: any) {
        const list = urls.map((item: any) => this.$staticUrl + "/" + item);
        dialogPreviewImg({
            title: "预览图片",
            current: list
        });
    }

    // 视频预览
    previewVideo(file: any) {
        dialogPreviewVideoAudio({
            sourceUrl: this.$staticUrl + "/" + file[0]
        });
    }

    // 提交
    completeTask() {
        this.$confirm("是否确认提交任务", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async() => {
                const res = await this.$server["task/complete"]({
                    data: {
                        taskId: this.$route.query.id
                    }
                });
                if (res.data.code === 200) {
                    this.$message.success("操作成功");
                    this.goBack();
                } else {
                    this.$message.error(res.data.message || "接口请求错误!");
                }
            })
            .catch();
    }

    // 指派
    assignRow() {
        dialogSelect({
            isSingle: true,
            tabs: [
                {
                    label: "村成员",
                    name: "village"
                }
            ],
            sure: async(vm: any, model: any) => {
                vm.close();
                if (model.selectedList.length) {
                    const res = await this.$server["collection/turnTask"]({
                        data: {
                            taskId: this.$route.query.id,
                            userId: model.selectedList[0]
                        }
                    });
                    if (res.data.code === 200) {
                        this.$message.success("操作成功");
                        this.goBack();
                    } else {
                        this.$message.error(res.data.message || "接口请求错误!");
                    }
                }
            },
            getOptions: (vm: any) => this.getOptions(vm)
        });
    }

    // 获取选项
    async getOptions(vm: any) {
        const res = await this.$server["collection/getGovernmentUser"]({
            data: {
                governmentId: this.authArea.governmentId
            },
            loader: false
        });
        if (res.data.code === 200) {
            const list = res.data.data.filter((item: any) => item.id !== this.user.id && item.orgCategoryId === "9");
            vm.getOptions(res.data.data ? list : []);
        } else {
            vm.getOptions([]);
        }
    }

    // 填报
    fillInRow() {
        const { formId } = this.$route.query;
        this.$router.push({
            name: "VillageDeclareFillIn",
            query: {
                id: formId,
                processInstanceId: this.$route.query.processInstanceId,
                name: this.$route.query.name,
                description: this.$route.query.description,
                descriptionType: this.$route.query.descriptionType
            }
        });
    }

    // 编辑选中行
    editRow(row: any) {
        const { formId, dataFormId } = row;
        this.$router.push({
            name: "VillageDeclareFillIn",
            query: {
                id: formId,
                dataFormId,
                processInstanceId: this.$route.query.processInstanceId,
                name: this.$route.query.name,
                description: this.$route.query.description,
                descriptionType: this.$route.query.descriptionType
            }
        });
    }

    // 删除行
    deleteRow(row: any) {
        const { formId, dataFormId } = row;
        this.$confirm("是否确定删除?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async() => {
                const res = await this.$server["moduleManage/fillForm/delete"]({
                    data: {
                        formId,
                        dataFormId
                    }
                });
                if (res.data.code === 200) {
                    this.$message.success("操作成功!");
                    await this.getTable();
                } else {
                    this.$message.error(res.data.message || "接口请求错误!");
                }
            })
            .catch();
    }

    goBack() {
        this.$router.back();
    }
}
</script>
<style scoped lang="scss">
::v-deep {
    .page-base-body {
        background: transparent!important;
    }
}

.right-btn {
    float: right;
}

.reject {
    font-size: 14px;
    color: #de2728;
    margin-top: 6px !important;
}

.task-detail-container {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    height: calc(100% - 100px);
    .left {
        width: 100%;
        height: 100%;
    }
}

.table-img {
    width: 120px;
    height: 80px;
    cursor: pointer;
    object-fit: contain;
}

.table-file {
    margin-right: 12px;
}

.acceptance-box {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    margin-top: 10px;
    .label {
        margin-right: 20px;
        line-height: 36px;
    }
    .right {
        p {
            margin: 5px 0 10px 0;
        }
    }
}
.preview-video {
    display: block;
    margin: 0 auto;
}

.import-btn {
    margin: 0 10px;
}
.isSingle {
    /deep/.el-table__header-wrapper {
        .el-checkbox {
            display: none;
        }
    }
}
.address-text {
    @include textEllipsis();
}

.task-detail-header {
    .title {
        p.description {
            font-size: 14px;
            max-width: 640px;
            @include textEllipsis();
        }
    }
    .btn {
        font-size: 14px;
        color: #2c82c9;
        cursor: pointer;
        &:hover {
            text-decoration: underline;
        }
    }
}
.rich-dialog {
    ::v-deep {
        .el-dialog__header {
            border-bottom: 1px solid #ccc;
        }
        .el-dialog__body {
            padding: 10px 20px;
            .titleName {
                font-size: 16px;
                padding: 0;
                margin: 0;
                margin-bottom: 10px;
            }
            .centent {
                max-height: 600px;
                overflow-y: scroll;
            }
        }
    }
}
</style>
